package br.com.players.service;

import java.util.List;

import javax.persistence.Query;

import br.com.players.model.Player;
import br.com.players.model.PlayerDefaultEntity;

public class CadastroPlayerService extends PlayersService {

	
	public List<Player> listarPlayers() {
		return (List<Player>) super.findAll(Player.class);
	}
	
	public void inserirPlayer(Player player) {
		super.persist(player);
	}
	
	public Player buscarPlayerPeloid(String id) {
		final Query query = em.createQuery("select p from Player p where p.id = :id");
		query.setParameter("id", Integer.parseInt(id));
		
		return (Player) query.getSingleResult();
	}
	
	public boolean playerExists(Player player) {
		final Query query = em.createQuery("select id from Player p where p.apelido = :apelido or p.email = :email");
		query.setParameter("apelido", player.getApelido());
		query.setParameter("email", player.getEmail());
		
		List<Player> resultList = query.getResultList();
		
		return resultList.size() > 0;
	}

	
	public void removerPlayer(Player player) {
		super.remove( player);
	}
	
	public void atualizarPlayer(Player player) {
		super.update(player);
	}
	
	public Player validarLogin(String apelido, String senha) {
		final Query query = em.createQuery("select p from Player p where p.apelido = :apelido and p.senha = :senha");
		query.setParameter("apelido", apelido);
		query.setParameter("senha", senha);
		
		List<Player> resultList = query.getResultList();
		
		return resultList.size() > 0 ? resultList.get(0) : null;
	}
	
	public Player buscarPlayerPeloNomeEmail(String nome, String email) {
		String where = "";
		if(nome != null && !nome.equals("")) {
			where = "where p.nome = :nome";
		}
		if(email != null && !email.equals("")) {
			where = "where p.email = :email";
		}
		final Query query = em.createQuery("select p from Player p " + where);
		query.setParameter("nome", nome);
		return (Player) query.getSingleResult();
		
	}
	
	public Player findPlayerByEmail(String email) {
		final Query query = em.createQuery("select p from Player p where p.email = :email");
		
		query.setParameter("email", email);
		
		List<Player> resultList = query.getResultList();
		
		return resultList.size() > 0 ? resultList.get(0) : null;
	}
}
